package com.txcb.lib.base.utils;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class InstallApkUtil {

    private static final String TAG = "InstallApkUtil";

    /**
     * 执行具体的静默安装逻辑，需要手机ROOT。
     *
     * @param apkPath 要安装的apk文件的路径
     * @return 安装成功返回true，安装失败返回false。
     */
    public static boolean installSilent(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader inputStream = null;
        try {
            Log.d(TAG,"pm install -r " + apkPath);
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = inputStream.readLine()) != null) {
                msg += line;
            }

//            LogUtil.d("install msg:"+msg);

            //LogUtils.d("pm install msg-->" + msg);
            if (msg.contains("Success")) {
                result = true;

            }
        } catch (Exception e) {
            e.printStackTrace();

//            ToastUtil.showToast("" + e);
        } finally {
            //LogUtils.d("pm install finally()");
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        LogUtil.d("installSilent result  "+ result);


        return result;
    }

    /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true，否则返回false。
     */
    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }


    //静默卸载
    public static void uninstallSlient(String PACKAGE_NAME) {

        String cmd = "pm uninstall " + PACKAGE_NAME;

        Process process = null;

        DataOutputStream os = null;

        BufferedReader successResult = null;

        BufferedReader errorResult = null;

        StringBuilder successMsg = null;

        StringBuilder errorMsg = null;

        try {

            process = Runtime.getRuntime().exec("su");

            os = new DataOutputStream(process.getOutputStream());

            os.write(cmd.getBytes());

            os.writeBytes("\n");

            os.writeBytes("exit\n");

            os.flush();

            //执行命令

            process.waitFor();

            //获取返回结果

            successMsg = new StringBuilder();

            errorMsg = new StringBuilder();

            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));

            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String s;

            while ((s = successResult.readLine()) != null) {

                successMsg.append(s);

            }

            while ((s = errorResult.readLine()) != null) {

                errorMsg.append(s);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                if (os != null) {

                    os.close();

                }

                if (process != null) {

                    process.destroy();

                }

                if (successResult != null) {

                    successResult.close();

                }

                if (errorResult != null) {

                    errorResult.close();

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        ToastUtil.showToast("已卸载成功");
        //显示结果

    }


    public static String getVersionName(Application context)   {
        // 获取packagemanager的实例
        try {
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            String version = packInfo.versionName;

            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 版本号比较
     *
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        LogUtil.d(  "version1Array=="+version1Array.length);
        LogUtil.d("version2Array=="+version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        LogUtil.d("verTag2=2222="+version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    private static void execLinuxCommand(){
        String cmd= "sleep 120; am start -n com.cbtx.tablet.activity.MainActivity";
        //Runtime对象
        Runtime runtime = Runtime.getRuntime();
        try {
            Process localProcess = runtime.exec("su");
            OutputStream localOutputStream = localProcess.getOutputStream();
            DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
            localDataOutputStream.writeBytes(cmd);
            localDataOutputStream.flush();
//            Logger.e("设备准备重启");
        } catch (IOException e) {
//            Logger.i(TAG+"strLine:"+e.getMessage());
            e.printStackTrace();

        }
    }


    /**
     * 打开安装包
     *
     * @param mContext
     * @param fileUri
     */
    public static void openAPKFile(Context mContext, String fileUri) {

        // 核心是下面几句代码
        if (null != fileUri) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                File apkFile = new File(fileUri);
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".FileProvider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    mContext.startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
//                LogUtils.d("e  :  " + e);
            }
        }

    }
}
